package com.cuiweiyou.bluemesh.util;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.annotation.RequiresApi;

/**
 *
 */

public class PermissionTool {
    public static int FLAG_REQUEST_PERMISSION = 101;
    public static int FLAG_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS = 111;

    public static void showPermissionRejectedDialog(final Activity activity) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle("无授权");                           // 标题
        builder.setMessage("没有权限继续进行，退出应用");   // 信息

        // 确定按钮
        builder.setPositiveButton("退出", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                activity.finish();
            }
        });

        AlertDialog dialog = builder.create();
        dialog.show();
    }

    public static void showPermissionDialog(Activity activity, final OnNeedPermissionAgreeBack back) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle("请授权");                           // 标题
        builder.setMessage("须要权限进行操作");   // 信息

        // 确定按钮
        builder.setPositiveButton("授权", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                back.agree(true);
            }
        });

        // 取消按钮
        builder.setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                back.agree(false);
            }
        });

        AlertDialog dialog = builder.create();
        dialog.show();
    }

    public static void requestPermissionFromSettingDialog(final Activity activity) {

        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle("请授权");
        builder.setMessage("缺少必要的权限，请去设置界面打开");

        // 确定按钮
        builder.setPositiveButton("前往设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startAppPermissionSettingActivity(activity);
            }
        });

        // 取消按钮
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                activity.finish();
            }
        });

        AlertDialog dialog = builder.create();
        dialog.show();
    }

    public static void startAppPermissionSettingActivity(Activity activity) {
        if (Build.MANUFACTURER.equalsIgnoreCase("xiaomi") || Build.BRAND.toLowerCase().equals("xiaomi")) {
            gotoMiuiPermission(activity);
        } else if (Build.MANUFACTURER.equalsIgnoreCase("huawei") || Build.BRAND.toLowerCase().equals("huawei")) {
            gotoHuaweiPermission(activity);
        } else if (Build.MANUFACTURER.equalsIgnoreCase("meizu") || Build.BRAND.toLowerCase().equals("meizu")) {
            gotoMeizuPermission(activity);
        } else if (Build.MANUFACTURER.equalsIgnoreCase("vivo") || Build.BRAND.toLowerCase().equals("vivo")) {
            gotoVivoPermission(activity);
        } else if (Build.MANUFACTURER.equalsIgnoreCase("oppo") || Build.BRAND.toLowerCase().equals("oppo")) {
            gotoOppoPermission(activity);
        } else if (Build.MANUFACTURER.equalsIgnoreCase("360") || Build.BRAND.toLowerCase().equals("360")) {
            goto360Permission(activity);
        } else if (Build.MANUFACTURER.equalsIgnoreCase("samsung") || Build.BRAND.toLowerCase().equals("samsung")) {
            gotoSamsungPermission(activity);
        } else if (Build.MANUFACTURER.equalsIgnoreCase("letv") || Build.BRAND.toLowerCase().equals("letv")) {
            gotoLetvPermission(activity);
        } else if (Build.MANUFACTURER.equalsIgnoreCase("smartisan") || Build.BRAND.toLowerCase().equals("smartisan")) {
            gotoSmartisanPermission(activity);
        } else {
            startAppSettingActivity(activity);
        }
    }

    /**
     * 跳转到miui的权限管理页面
     */
    private static void gotoMiuiPermission(Activity activity) {
        try {
            Intent i = new Intent("miui.intent.action.APP_PERM_EDITOR");
            ComponentName componentName = new ComponentName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
            i.setComponent(componentName);
            i.putExtra("extra_pkgname", activity.getPackageName());

            activity.startActivityForResult(i, FLAG_REQUEST_PERMISSION);
        } catch (Exception e) {
            try {
                Intent i = new Intent("miui.intent.action.APP_PERM_EDITOR");
                ComponentName componentName = new ComponentName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity");
                i.setComponent(componentName);
                i.putExtra("extra_pkgname", activity.getPackageName());

                activity.startActivity(i);
            } catch (Exception e1) {
                e1.printStackTrace();
                startAppSettingActivity(activity);
            }
        }
    }

    /**
     * 跳转到魅族的权限管理系统
     */
    private static void gotoMeizuPermission(Activity activity) {
        Intent i = new Intent("com.meizu.safe.security.SHOW_APPSEC");
        i.addCategory(Intent.CATEGORY_DEFAULT);
        i.putExtra("packageName", activity.getPackageName());
        try {
            activity.startActivityForResult(i, FLAG_REQUEST_PERMISSION);
        } catch (Exception e) {
            e.printStackTrace();
            gotoMeizuPermission2(activity);
        }
    }

    /**
     * 跳转到魅族的权限管理系统
     */
    private static void gotoMeizuPermission2(Activity activity) {
        try {
            Intent intent = activity.getPackageManager().getLaunchIntentForPackage("com.meizu.safe");
            activity.startActivityForResult(intent, FLAG_REQUEST_PERMISSION);
        } catch (Exception e3) {
            startAppSettingActivity(activity);
        }
    }

    /**
     * 华为的权限管理页面
     */
    private static void gotoHuaweiPermission(Activity activity) {
        try {
            Intent i = new Intent();
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ComponentName comp = new ComponentName("com.huawei.systemmanager", "com.huawei.permissionmanager.ui.MainActivity");//华为权限管理
            i.setComponent(comp);
            activity.startActivityForResult(i, FLAG_REQUEST_PERMISSION);
        } catch (Exception e) {
            e.printStackTrace();
            gotoHuaweiPermission2(activity);
        }
    }

    /**
     * 华为的权限管理页面
     */
    private static void gotoHuaweiPermission2(Activity activity) {
        try {
            Intent i = new Intent();
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ComponentName comp = new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.startupmgr.ui.StartupNormalAppListActivity");//华为权限管理
            i.setComponent(comp);
            activity.startActivityForResult(i, FLAG_REQUEST_PERMISSION);
        } catch (Exception e) {
            e.printStackTrace();
            gotoHuaweiPermission3(activity);
        }
    }

    /**
     * 华为的权限管理页面
     */
    private static void gotoHuaweiPermission3(Activity activity) {
        try {
            Intent i = new Intent();
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ComponentName comp = new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.bootstart.BootStartActivity");//华为权限管理
            i.setComponent(comp);
            activity.startActivityForResult(i, FLAG_REQUEST_PERMISSION);
        } catch (Exception e) {
            e.printStackTrace();
            startAppSettingActivity(activity);
        }
    }

    /**
     * vivo的权限管理页面
     */
    private static void gotoVivoPermission(Activity activity) {
        try {
            Intent i = new Intent();
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ComponentName comp = new ComponentName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.PurviewTabActivity");//vivo X9L权限管理
            i.setComponent(comp);
            activity.startActivityForResult(i, FLAG_REQUEST_PERMISSION);
        } catch (Exception e) {
            try {
                Intent intent = activity.getPackageManager().getLaunchIntentForPackage("com.iqoo.secure");
                if (intent != null) {
                    activity.startActivityForResult(intent, FLAG_REQUEST_PERMISSION);
                } else {
                    startAppSettingActivity(activity);
                }
            } catch (Exception e1) {
                e1.printStackTrace();
                startAppSettingActivity(activity);
            }
        }
    }

    /**
     * oppo的权限管理页面
     */
    private static void gotoOppoPermission(Activity activity) {
        try {
            Intent intent = activity.getPackageManager().getLaunchIntentForPackage("com.oppo.safe");
            if (intent != null) {
                activity.startActivityForResult(intent, FLAG_REQUEST_PERMISSION);
            } else {
                startAppSettingActivity(activity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            gotoOppoPermission2(activity);
        }
    }

    /**
     * oppo的权限管理页面
     */
    private static void gotoOppoPermission2(Activity activity) {
        try {
            Intent intent = activity.getPackageManager().getLaunchIntentForPackage("com.coloros.phonemanager");
            activity.startActivityForResult(intent, FLAG_REQUEST_PERMISSION);
        } catch (Exception e1) {
            try {
                Intent intent = activity.getPackageManager().getLaunchIntentForPackage("com.coloros.oppoguardelf");
                activity.startActivityForResult(intent, FLAG_REQUEST_PERMISSION);
            } catch (Exception e3) {
                gotoOppoPermission3(activity);
            }
        }
    }

    /**
     * oppo的权限管理页面
     */
    private static void gotoOppoPermission3(Activity activity) {
        try {
            Intent intent = activity.getPackageManager().getLaunchIntentForPackage("com.coloros.safecenter");
            activity.startActivityForResult(intent, FLAG_REQUEST_PERMISSION);
        } catch (Exception e3) {
            startAppSettingActivity(activity);
        }
    }

    /**
     * 360的权限管理页面
     */
    private static void goto360Permission(Activity activity) {
        try {
            // com.qiku.android.security/.ui.activity.AppSecurityMainListActivity
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ComponentName comp = new ComponentName("com.qiku.android.security", "com.qiku.android.security.ui.activity.AppSecurityMainListActivity");
            intent.setComponent(comp);
            activity.startActivityForResult(intent, FLAG_REQUEST_PERMISSION);
        } catch (Exception e) {
            startAppSettingActivity(activity);
        }
    }

    /**
     * 三星的权限管理页面
     */
    private static void gotoSamsungPermission(Activity activity) {
        try {
            Intent intent = activity.getPackageManager().getLaunchIntentForPackage("com.samsung.android.sm_cn");
            activity.startActivityForResult(intent, FLAG_REQUEST_PERMISSION);
        } catch (Exception e) {
            gotoSamsungPermission2(activity);
        }
    }

    /**
     * 三星的权限管理页面
     */
    private static void gotoSamsungPermission2(Activity activity) {
        try {
            Intent intent = activity.getPackageManager().getLaunchIntentForPackage("com.samsung.android.sm");
            activity.startActivityForResult(intent, FLAG_REQUEST_PERMISSION);
        } catch (Exception e) {
            startAppSettingActivity(activity);
        }
    }

    /**
     * 锤子的权限管理页面
     */
    private static void gotoSmartisanPermission(Activity activity) {
        try {
            Intent intent = activity.getPackageManager().getLaunchIntentForPackage("com.smartisanos.security");
            activity.startActivityForResult(intent, FLAG_REQUEST_PERMISSION);
        } catch (Exception e) {
            startAppSettingActivity(activity);
        }
    }

    /**
     * 乐视的权限管理页面
     */
    private static void gotoLetvPermission(Activity activity) {
        try {
            Intent i = new Intent();
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ComponentName comp = new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.AutobootManageActivity");
            i.setComponent(comp);
            activity.startActivityForResult(i, FLAG_REQUEST_PERMISSION);
        } catch (Exception e) {
            startAppSettingActivity(activity);
        }
    }

    private static void startAppSettingActivity(Activity activity) {
        activity.startActivityForResult(getAppDetailSettingIntent(activity), FLAG_REQUEST_PERMISSION);
    }

    /**
     * 获取应用详情页面intent
     *
     * @return
     */
    private static Intent getAppDetailSettingIntent(Context context) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            //  localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
        }
        return localIntent;
    }

    public interface OnNeedPermissionAgreeBack {
        void agree(boolean authorized);
    }

    /**
     * 是否存在于白名单
     *
     * @param context
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public static boolean isIgnoringBatteryOptimizations(Context context) {
        boolean isIgnoring = false;
        PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        if (powerManager != null) {
            isIgnoring = powerManager.isIgnoringBatteryOptimizations(context.getPackageName());
        }
        return isIgnoring;
    }

    /**
     * 申请加入白名单
     *
     * @param context
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public static void requestIgnoreBatteryOptimizations(Activity context) {
        try {
            Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + context.getPackageName()));
            context.startActivityForResult(intent, FLAG_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

